import { getTreeApi } from "@/api/dish";
import { addSetmealApi, getSetmealDetailApi, updateSetmealApi } from "@/api/setmeal";
import { useSetmealCatetory } from "@/hooks/useCatetory";
import { useUserStore } from "@/stores/user";
import { AddSetmealData, setmealDisheItem } from "@/types/setmeal";
import { message } from "@/utils/AntdGlobal";
import { PlusOutlined } from "@ant-design/icons";
import { Card, FormProps, InputNumber, Upload, UploadFile, UploadProps } from "antd";
import TextArea from "antd/es/input/TextArea";


export function Component() {
  const { Option } = Select;
  // 获取表单
  const [form] = Form.useForm();
  const navigate = useNavigate();
  // 获取传过来的id
  const [params] = useSearchParams();
  const setmealId = params.get('id')
  // 获取菜品分类
  const { categoryList: setCategoryList } = useSetmealCatetory()
  const onFinish: FormProps<AddSetmealData>['onFinish'] = async (values) => {
    if (setmealId) {
      await updateSetmealApi({
        categoryId: values.categoryId,
        description: values.description,
        image: fileList[0].url! || fileList[0].response.data,
        name: values.name,
        price: values.price,
        setmealDishes: defaultValue!,
        id: +setmealId
      })
      message.success('修改成功')
    } else {
      await addSetmealApi({
        categoryId: values.categoryId,
        description: values.description,
        image: fileList[0].response.data,
        name: values.name,
        price: values.price,
        setmealDishes: defaultValue!
      })
      message.success('添加成功')
    }
    navigate(-1)
  };
  interface Option {
    value?: string | number | null;
    label: React.ReactNode;
    children?: Option[];
    isLeaf?: boolean;
  }

  const [options, setOptions] = useState<Option[]>([]);
  // 获取数据（前端进行处理，目前舍弃，使用后端接口进行处理）
  // useMemo(() => {
  //   const getList = async () => {
  //     const res = await getCategoryListByTypeApi()
  //     const arr = await Promise.all(res.data.map(async item => {
  //       const { data } = await getDishListByIdApi(+item.id)
  //       const children = data.map(item => {
  //         return {
  //           value: item.id,
  //           label: item.name,
  //           price: item.price,
  //           copies: Math.floor(Math.random() * 3) + 1
  //         }
  //       })
  //       return {
  //         value: item.id,
  //         label: item.name,
  //         isLeaf: false,
  //         children
  //       }
  //     }))
  //     setOptions(arr)
  //   }
  //   getList()
  // }, [])
  // 获取路由
  useEffect(() => {
    const getDishDetail = async () => {
      const res = await getSetmealDetailApi(+setmealId!)
      form.setFieldsValue({
        ...res.data,
        setmealDishes: res.data.setmealDishes.map(item => {
          return [
            item.categoryId, item.dishId
          ]
        })
      })
      // 回显图片
      setFileList([{
        uid: '',
        name: '',
        url: res.data.image
      }])
    }
    if (setmealId) {
      getDishDetail()
    }
    // 获取树数据（使用后端接口进行处理）
    const getTree = async () => {
      const res = await getTreeApi()
      const arr = res.data.map(item => {
        const children = item.children.map(item => {
          return {
            value: item.id,
            label: item.name,
            price: item.price,
            copies: Math.floor(Math.random() * 3) + 1
          }
        })
        return {
          value: item.id,
          label: item.name,
          isLeaf: item.isLeaf,
          children
        }
      })
      setOptions(arr)
    }
    getTree()
  }, [])
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) => {
    setFileList(newFileList);
  }
  /**
   * 添加菜品使用随机数
   */
  // 口味的默认值

  const [defaultValue, setDefaultValue] = useState<setmealDisheItem[]>()
  // 改变口味
  // const changeFlavour = async (data: string[]) => {
  //   const arr = await Promise.all(data.map(async (id) => {
  //     const { data } = await getDishListByIdApi(+id)
  //     // 获取随机数
  //     const index = Math.floor(Math.random() * data.length) + 1
  //     return data.slice(0, index)
  //   }))
  //   const setmealDishes = arr.flat(1).reduce((prev: setmealDisheItem[], item) => {
  //     prev.push({
  //       dishId: item.id,
  //       name: item.name,
  //       price: item.price,
  //       copies: Math.floor(Math.random() * 3) + 1
  //     })
  //     return prev
  //   }, [])
  //   setDefaultValue(setmealDishes)
  // }
  const onChange = (_value: any, selectedOptions: any) => {
    // console.log(value, selectedOptions);
    const arr = selectedOptions.map((item: string | any[]) => {
      const dishData = item[1]
      return { ...dishData, ...item[1] }
    })
    const newArr = arr.map((item: {
      value: number,
      label: string,
      price: number,
      copies: number
    }) => {
      return {
        dishId: item.value,
        name: item.label,
        price: item.price,
        copies: item.copies
      }
    })
    setDefaultValue(newArr)
  };
  return (
    <div style={{ width: '100%', height: '100%', overflow: 'hidden' }}>
      {/* 查询 */}
      <Card className="mb-4" size="small">
        <div className="flex flex-justify-between flex-items-center">
          <div className="font-bold font-size-4">{setmealId ? '修改套餐' : '添加套餐'}</div>
          <Button type="primary" onClick={() => navigate(-1)}>
            返回
          </Button>
        </div>
      </Card>
      {/* 表格 */}
      <Card style={{ overflow: 'auto', height: '100%' }}>
        <div className="flex flex-justify-center">
          <Form
            name="basic"
            form={form}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 16 }}
            style={{ minWidth: 800 }}
            initialValues={{ sex: '1' }}
            onFinish={onFinish}
            autoComplete="off"
          >
            <Form.Item<AddSetmealData>
              label="套餐名称"
              name="name"
              rules={[{ required: true, message: '请输入套餐名称!' }]}
            >
              <Input placeholder="请输入套餐名称" />
            </Form.Item>

            <Form.Item<AddSetmealData> name="categoryId" label="套餐分类" rules={[{ required: true, message: '请输入套餐价格!' }]}>
              <Select
                placeholder="请选择套餐分类"
                allowClear
              >
                {setCategoryList.map(item => <Option key={item.id} value={item.id}>{item.name}</Option>)}
              </Select>
            </Form.Item>

            <Form.Item<AddSetmealData>
              label="套餐价格"
              name="price"
              rules={[{ required: true, message: '请输入套餐价格!' }]}
            >
              <InputNumber style={{ width: "100%" }} min={0} max={10000} placeholder="请输入套餐价格" />
            </Form.Item>
            <Form.Item<AddSetmealData> label="套餐菜品" name="setmealDishes" rules={[{ required: true, message: '请输入选择套餐菜品!' }]}>
              {/* <Select
                placeholder="套餐菜品"
                allowClear
                mode="multiple"
                style={{ width: "100%" }}
                onChange={(value) => changeFlavour(value)}
              >
                {categoryList.map(item => <Option key={item.id} value={item.id}>{item.name}</Option>)}
              </Select> */}
              <Cascader options={options} placeholder="套餐菜品" multiple maxTagCount={"responsive"} showCheckedStrategy="SHOW_CHILD" onChange={onChange} changeOnSelect />
            </Form.Item>
            <Form.Item label="套餐图片" name="image" rules={[{ required: true, message: '请上传图片!' }]}>
              <Upload
                action={"http://localhost:9000/api/admin/common/upload"}
                listType="picture-card"
                maxCount={1}
                accept="image/*"
                name="file"
                fileList={fileList}
                onChange={handleChange}
                headers={{ token: useUserStore.getState().token }}
              >
                <button style={{ border: 0, background: 'none' }} type="button">
                  <PlusOutlined />
                  <div style={{ marginTop: 8 }}>上传图片</div>
                </button>
              </Upload>
            </Form.Item>
            <Form.Item<AddSetmealData>
              label="套餐描述"
              name="description"
            >
              <TextArea rows={4} placeholder="请输入套餐描述" />
            </Form.Item>
            <Form.Item wrapperCol={{ span: 24 }}>
              <div className="flex flex-justify-center mr-8">
                <Button type="default" onClick={() => navigate(-1)} className="mr-8">
                  取消
                </Button>
                <Button type="primary" htmlType="submit">
                  {setmealId ? "修改" : '添加'}
                </Button>
              </div>
            </Form.Item>
          </Form>
        </div>
      </Card >
    </div >
  )
}